﻿#if BACKEND
using GameData.Domains;
using GameData.Domains.Character;
using GameData.Domains.Character.Relation;
using GameData.Domains.Character.Display;
using GameData.Domains.Item;
using GameData.Domains.Map;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using Character = GameData.Domains.Character.Character;
using static NpcScan.Const;
namespace NpcScan
{
    public partial class CharacterData
    {
        public static unsafe int GetName(int id){
            // var name=new byte[NameLength];
            if(!NMdict.ContainsKey(id)){
                NameRelatedData nameRelatedData=DomainManager.Character.GetNameRelatedData(id);
                // fixed(byte*x=name){
                //     nameRelatedData.Serialize(x);
                // }
                // return name;
                var display_name=nameRelatedData.GetMonasticTitleOrDisplayName(false);
                var real_name=nameRelatedData.GetRealName();
                if(display_name!=real_name) {
                    NMdict[id]=$"{real_name.Item1+real_name.Item2}\n({display_name.Item1+display_name.Item2})";
                } else {
                    NMdict[id]=$"{real_name.Item1+real_name.Item2}";
                }
            }
            return id;
        }
        static FieldInfo _combatPower=typeof(Character).GetField("_combatPower",(BindingFlags)(-1));
        public unsafe void SetData(Character character)
        {
            // isAlive = 1; // in gender
            id = character.GetId();
            state = character.GetExternalRelationState();
            name=GetName(id);
            curr = character.GetCurrAge();
            age = character.GetActualAge();
            mood = character.GetHappiness();
            xiangshuInfection = character.GetXiangshuInfection();
            gender = 1<<24 | (character.GetTransgender()?1<<16:0) | (character.GetBisexual()?1<<8:0) | (byte)character.GetGender() ;

            Location tempLocation = character.GetLocation();

            location = new short[2] { tempLocation.AreaId, tempLocation.BlockId };

            attraction = character.GetAttraction();
            creatingType = character.GetCreatingType();
            // transgender = character.GetTransgender();
            // bisexual = character.GetBisexual();

            OrganizationInfo tempOrganizationInfo = character.GetOrganizationInfo();
            organizationInfo = new short[4] { tempOrganizationInfo.OrgTemplateId, tempOrganizationInfo.Grade, Convert.ToInt16(tempOrganizationInfo.Principal), tempOrganizationInfo.SettlementId };

            behaviorType = character.GetBehaviorType();

            marriage=Marriage(id);
            power=(int)_combatPower.GetValue(character);
            extra_neili=character.GetExtraNeili();
            max_neili=character.GetMaxNeili();
            jingchun=character.GetConsummateLevel();

            lifeSkillGrowthType = character.GetLifeSkillQualificationGrowthType();
            combatSkillGrowthType = character.GetCombatSkillQualificationGrowthType();
            health = character.GetHealth();
            maxLeftHealth = character.GetLeftMaxHealth(character.IsCompletelyInfected());
            LegendaryBookOwnerState=character.GetLegendaryBookOwnerState();
            FavorabilityToTaiwu=DomainManager.Character.GetFavorability(id, Backend.taiwuCharId);
            MainAttributes tempMaxMainAttributes = character.GetMaxMainAttributes();
            maxMainAttributes = new short[6];
            for (int index = 0; index < 6; index++)
            {
                maxMainAttributes[index] = tempMaxMainAttributes.Items[index];
            }

            LifeSkillShorts tempLifeSkillQualifications = character.GetLifeSkillQualifications();
            lifeSkillQualifications = new short[16];
            for (int index = 0; index < 16; index++)
                lifeSkillQualifications[index] = tempLifeSkillQualifications.Items[index];

            CombatSkillShorts tempCombatSkillQualifications = character.GetCombatSkillQualifications();
            combatSkillQualifications = new short[14];
            for (int index = 0; index < 14; index++)
                combatSkillQualifications[index] = tempCombatSkillQualifications.Items[index];


            List<ItemBase> itemList = (from itemKey in character.GetInventory().Items.Keys
                where itemKey.ItemType!=-1
                select DomainManager.Item.GetBaseItem(itemKey)
            ).ToList();
            foreach (var equipment in character.GetEquipment())
            {
                if (equipment.ItemType == -1)
                    continue;
                itemList.Add(DomainManager.Item.GetBaseItem(equipment));
            }
            items=(from item in itemList
                orderby item.GetGrade() descending, item.GetItemType(), item.GetItemSubType()
                select ToItem(item.GetGrade(), item.GetItemType(), item.GetTemplateId())
            ).ToArray();


            samsara = Samsara(character.GetPreexistenceCharIds());
            featureIds = character.GetFeatureIds().ToArray();
            potentialFeatureIds = character.GetPotentialFeatureIds().ToArray();
            faction=character.GetFactionId();
            kidnapper=character.GetKidnapperId();
            leader=character.GetLeaderId();
            ideal=((byte)character.GetIdealSect())|((int)(character.GetLoopingNeigong()<<16));
        }

        public unsafe void SetDeadData(int id, DeadCharacter character, Location location, List<ItemKey> itmlst)
        {
            // isAlive = 0; // merged into character.Gender directly.
            this.id = id;
            this.faction = -1;
            this.leader = -1;
            this.kidnapper = -1;
            this.ideal = -1;
            this.curr = -1;

            name=GetName(id);

            age = character.GetActualAge();
            gender = (byte)character.Gender;
            // transgender = bisexual = false; // no data.

            mood = character.Happiness;
            this.location = new short[2] { location.AreaId, location.BlockId };
            attraction = character.Attraction;
            creatingType = 1;

            OrganizationInfo tempOrganizationInfo = character.OrganizationInfo;
            organizationInfo = new short[4] { tempOrganizationInfo.OrgTemplateId, tempOrganizationInfo.Grade, Convert.ToInt16(tempOrganizationInfo.Principal), tempOrganizationInfo.SettlementId };

            behaviorType = GameData.Domains.Character.BehaviorType.GetBehaviorType(character.Morality);

            marriage=Marriage(id);
            power=-1;
            extra_neili=-1;
            max_neili=-1;
            jingchun=character.GetConsummateLevel();

            lifeSkillGrowthType = 0;
            combatSkillGrowthType = 0;
            health = 0;
            maxLeftHealth = 0;

            LegendaryBookOwnerState=-1;
            FavorabilityToTaiwu=DomainManager.Character.GetFavorability(id, Backend.taiwuCharId);
            MainAttributes tempMaxMainAttributes = character.BaseMainAttributes;
            maxMainAttributes = new short[6];
            for (int index = 0; index < 6; index++)
            {
                maxMainAttributes[index] = tempMaxMainAttributes.Items[index];
            }

            LifeSkillShorts tempLifeSkillQualifications = character.BaseLifeSkillQualifications;
            lifeSkillQualifications = new short[16];
            for (int index = 0; index < 16; index++)
                lifeSkillQualifications[index] = tempLifeSkillQualifications.Items[index];

            CombatSkillShorts tempCombatSkillQualifications = character.BaseCombatSkillQualifications;
            combatSkillQualifications = new short[14];
            for (int index = 0; index < 14; index++)
                combatSkillQualifications[index] = tempCombatSkillQualifications.Items[index];

            if(itmlst!=null){
                items=(from itemKey in itmlst
                    where itemKey.ItemType!=-1
                    let item = DomainManager.Item.GetBaseItem(itemKey)
                    orderby item.GetGrade() descending, item.GetItemType(), item.GetItemSubType()
                    select ToItem(item.GetGrade(), item.GetItemType(), item.GetTemplateId())
                ).ToArray();
            }else{
                items=new int[0];
            }

            samsara = Samsara(character.PreexistenceCharIds);
            featureIds = character.FeatureIds.ToArray();
            potentialFeatureIds = new short[0];
        }
        public static byte Marriage(int id){
            var mates = DomainManager.Character.GetRelatedCharIds(id, RelationType.HusbandOrWife);
            if (mates.Count > 0) {
                foreach (int mateId in mates) {
                    if (DomainManager.Character.IsCharacterAlive(mateId))
                    {
                        return 1;
                    }
                    return 2;
                }
            }
            return 0;
        }
        public unsafe static int[] Samsara(PreexistenceCharIds ids){
            var lst=new int[ids.Count];
            for(int i=0;i<ids.Count;i++){
                lst[i]=GetName(ids.CharIds[i]);
            }
            return lst;
        }
    }
}
#endif
